package com.uduemc.biso.node.web.api.controller.noauthentication.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.Agent;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.web.api.service.AgentService;

import cn.hutool.core.util.StrUtil;

@RequestMapping("/api/service/agent")
@Controller
public class ASAgentController {

	@Autowired
	private AgentService agentServiceImpl;

	@PostMapping("/bind-node-domain")
	@ResponseBody
	public RestResult bindNodeDomain(@RequestParam("agentId") Long agentId, @RequestParam("domainName") String domainName,
			@RequestParam("universalDomainName") String universalDomainName)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (agentId == null || agentId.longValue() < 1) {
			Map<String, Object> message = new HashMap<>();
			message.put("agentId", "传递的参数异常！ agentId: " + agentId);
			return RestResult.error(message);
		}
		if (StrUtil.isBlank(domainName)) {
			Map<String, Object> message = new HashMap<>();
			message.put("domainName", "传递的参数异常！ domainName 为空。");
			return RestResult.error(message);
		}
		if (StrUtil.isBlank(universalDomainName)) {
			Map<String, Object> message = new HashMap<>();
			message.put("universalDomainName", "传递的参数异常！ universalDomainName 为空。");
			return RestResult.error(message);
		}

		// 通过 agentId 获取到 agent 数据信息
		Agent agent = agentServiceImpl.info(agentId);
		if (agent == null) {
			Map<String, Object> message = new HashMap<>();
			message.put("agentId", "未能通过 agentId 从主控端 home 获取到 Agent 数据！ agentId: " + agentId);
			return RestResult.error(message);
		}

		// 绑定代理商节点域名 domainName
		if (!agentServiceImpl.bindNodeDomain(agent, domainName, universalDomainName)) {
			Map<String, Object> message = new HashMap<>();
			message.put("bindNodeDomain", "节点绑定域名失败！ domainName: " + domainName);
			return RestResult.error(message);
		}

		return RestResult.ok(1);
	}

}
